package com.xmb.wpclient.utils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmb.wpclient.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class HttpRequestUtils {

	@Value("${constant.uploadUrl}")
	private String uploadUrl;
	
	public ResultVO httpRequest(String param) {
		System.out.println(param);
		/** 网络的url地址 */
		URL url = null;
		HttpURLConnection httpUrlConnection = null ;
		DataOutputStream  out = null; //写
		InputStream inputStream = null; //读
		BufferedReader in = null;
		String result = null;
		try {
			url = new URL(uploadUrl);
			httpUrlConnection = (HttpURLConnection) url.openConnection();
			httpUrlConnection.setConnectTimeout(5000);
			httpUrlConnection.setReadTimeout(5000);
			httpUrlConnection.setRequestMethod("POST");
			// Post 请求不能使用缓存
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
			//传入参数
			if(StringUtils.isNotEmpty(param)) {
				httpUrlConnection.setDoOutput(true);
				out = new DataOutputStream(httpUrlConnection.getOutputStream());
//				out.writeBytes(param);
				out.write(param.getBytes("UTF-8"));
				out.flush();
		        out.close();
			}
			inputStream = httpUrlConnection.getInputStream();

			in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String res;
			while ((res = in.readLine()) != null) {
				result = res;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			httpUrlConnection.disconnect();
		}
		return JSON.parseObject(result, ResultVO.class);
	}
}
